package com.client.service.impl;

import com.Emplyment.entity.Article;
import com.Emplyment.entity.CompanyCollect;
import com.Emplyment.exception.BaseException;
import com.Emplyment.util.CacheHotCompany;
import com.Emplyment.utils.SearchUtil;
import com.Emplyment.vo.CategoriesVo;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.client.mapper.CompanyMapper;
import com.client.service.CompanyService;
import lombok.extern.slf4j.Slf4j;
import netscape.javascript.JSObject;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private static final String companyHASH_KEY = "company:HASH:data";

    @Override
    public List<Article> getCompany(Integer categoryId) {
        List<Article> companyList = new ArrayList<>();
        if (Boolean.TRUE.equals(redisTemplate.hasKey(companyHASH_KEY))) {
            log.info("从redis中获取公司信息");
            Map<String, Object> entries = redisTemplate.opsForHash().entries(companyHASH_KEY);
            for (Map.Entry<String, Object> entry : entries.entrySet()) {
                CacheHotCompany cacheHotCompany = JSONObject.parseObject(entry.getValue().toString(), new TypeReference<CacheHotCompany>() {
                });
                Article company = cacheHotCompany.getCompany();
                if (categoryId == 0 || company.getCategoryId().equals(categoryId)) {
                    companyList.add(company);
                }
            }
        }else{
            log.info("redis中没有公司信息，从数据库中获取");
            if (categoryId == 0) {
                companyList = companyMapper.getCompany();
            } else {
                companyList = companyMapper.ByCategoryIdCompany(categoryId);
            }
        }
        return companyList;
    }

    /**
     * 收藏
     * @param collect
     */
    @Override
    public void collect(CompanyCollect collect) {
        //将收藏信息存入收藏中
        companyMapper.collect(collect);
        //要修改对应公司的收藏数
        companyMapper.updateCollectCount(collect.getCompanyId());
        //将收藏信息存入redis中
    }

    /**
     * 取消收藏
     * @param collect
     */
    @Override
    public void canceCollect(CompanyCollect collect) {
        companyMapper.canceCollect(collect);
        companyMapper.updateCancelCollectCount(collect.getCompanyId());
    }

    @Override
    public Integer getCompanyStatus(CompanyCollect collect) {
        Integer companyStatus = companyMapper.getCompanyStatus(collect);
        return companyStatus;
    }

    /**
     * 搜索公司
     * @param keyword
     * @return
     */
    @Override
    public List<Article> searchCompany(String keyword) {
        List<Article> list = new ArrayList<>();
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("app_emplyment_message");
            // 2.准备DSL
            request.source()
                    .query(QueryBuilders.matchQuery("title", keyword));
            // 3.发送请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4.解析响应

            // 4.解析响应
            SearchHits searchHits = response.getHits();
            // 4.1.获取总条数
            long total = searchHits.getTotalHits().value;
            System.out.println("共搜索到" + total + "条数据");
            // 4.2.文档数组
            SearchHit[] hits = searchHits.getHits();
            // 4.3.遍历
            for (SearchHit hit : hits) {
                // 获取文档source
                String json = hit.getSourceAsString();
                // 解析json
                Article article = JSONObject.parseObject(json, Article.class);
                list.add(article);
            }
        return list;

        }catch (Exception e){
            throw new BaseException("搜索公司失败");
        }
    }

    @Override
    public List<CategoriesVo> getCategories() {
        List<CategoriesVo> categoriesVos = companyMapper.getCategories();
        return categoriesVos;
    }


}
